import 'package:flutter/foundation.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter_draggable_gridview/flutter_draggable_gridview.dart';

class DraggableGridViewDemo extends StatefulWidget {
  const DraggableGridViewDemo({Key? key}) : super(key: key);

  @override
  State<DraggableGridViewDemo> createState() => _DraggableGridViewDemoState();
}

class _DraggableGridViewDemoState extends State<DraggableGridViewDemo> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Draggable GridView'),
      ),
      body: DraggableGridViewBuilder(
        gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
          crossAxisCount: 2,
          childAspectRatio: MediaQuery.of(context).size.width /
              (MediaQuery.of(context).size.height / 3),
        ),
        children: _makeGridItems(12),
        isOnlyLongPress: true,
        dragCompletion:
            (List<DraggableGridItem> list, int beforeIndex, int afterIndex) {
          if (kDebugMode) {
            print('onDragAccept: $beforeIndex -> $afterIndex');
          }
        },
        dragFeedback: (List<DraggableGridItem> list, int index) {
          return SizedBox(
            width: 200,
            height: 150,
            child: list[index].child,
          );
        },
        dragStartBehavior: DragStartBehavior.start,
        dragPlaceHolder: (List<DraggableGridItem> list, int index) {
          return PlaceHolderWidget(
            child: Container(
              color: Colors.blue[100],
            ),
          );
        },
      ),
    );
  }

  List<DraggableGridItem> _makeGridItems(int count) {
    var colors = [
      Colors.blue,
      Colors.red[400],
      Colors.amber,
      Colors.orange,
      Colors.purple
    ];
    var assetsName = [
      'images/earth.jpeg',
      'images/fire.png',
      'images/girl.jpeg',
      'images/island-coder.png',
      'images/mb.jpeg'
    ];
    return List.generate(
      count,
      (index) => DraggableGridItem(
        isDraggable: true,
        dragCallback: (_, isDragging) {
          debugPrint('{$index}在拖拽：{$isDragging}');
        },
        child: Image.asset(
          assetsName[index % assetsName.length],
          fit: BoxFit.cover,
        ),
      ),
    );
  }
}
